<template>
  <div class="medication-container">
    <div class="vertical-warning">哈基米曼波</div>
    <h3><i class="fas fa-allergy"></i>过敏史管理</h3>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button
          v-if="!editMode"
          type="primary"
          @click="editMode = true"
          icon="el-icon-edit"
          class="action-btn"
      >编辑
      </el-button>
      <el-button
          v-if="!editMode"
          type="success"
          @click="addNewMedication"
          icon="el-icon-plus"
          class="action-btn"
      >新增
      </el-button>
      <el-button
          v-if="!editMode"
          type="warning"
          @click="toggleSort"
          icon="el-icon-sort"
          class="action-btn"
      >{{ sortButtonText }}
      </el-button>

      <template v-else>
        <el-button
            type="success"
            @click="saveChanges"
            icon="el-icon-check"
            class="confirm-btn"
        >保存
        </el-button>
        <el-button
            type="danger"
            @click="cancelEdit"
            icon="el-icon-close"
            class="cancel-btn"
        >取消
        </el-button>
      </template>
    </div>

    <div class="medication-list">
      <div
          class="medication-card"
          :class="{ 'sample-data': isSampleData }"
          v-for="(med, index) in medications"
          :key="med.recordId || index"
          @mousedown="createRipple"
      >
        <div class="medication-header">
          <span class="detail-label"><i class="far fa-clock"></i> ID:{{ med.recordId }}</span>


        </div>

        <!-- 过敏史具体字段 -->
        <div class="medication-details">
          <div class="detail-item">
            <label>过敏原:</label>
            <span v-if="!editMode">{{ med.allergen || '未填写' }}</span>
            <el-input v-else v-model="med.allergen" placeholder="请输入过敏原"></el-input>
          </div>
          <div class="detail-item">
            <label>禁用药物:</label>
            <span v-if="!editMode">{{ med.forbiddenDrugs || '未填写' }}</span>
            <el-input v-else v-model="med.forbiddenDrugs" placeholder="请输入禁用药物"></el-input>
          </div>
          <div class="detail-item">
            <label>治疗药物:</label>
            <span v-if="!editMode">{{ med.treatmentDrugs || '未填写' }}</span>
            <el-input v-else v-model="med.treatmentDrugs" placeholder="请输入治疗药物"></el-input>
          </div>
          <div class="detail-item">
            <label>规避方法:</label>
            <span v-if="!editMode">{{ med.avoidanceMethod || '未填写' }}</span>
            <el-input v-else v-model="med.avoidanceMethod" placeholder="请输入规避方法"></el-input>
          </div>
          <div class="detail-item">
            <label>备注:</label>
            <span v-if="!editMode">{{ med.remarks || '暂无备注' }}</span>
            <el-input v-else v-model="med.remarks" type="textarea" autosize></el-input>
          </div>
        </div>
        <!-- 删除按钮放在每张卡片内 -->
        <div class="card-actions" v-if="editMode">
          <el-button
              type="danger"
              size="small"
              @click="deleteHandler(index)"
              icon="el-icon-delete"
          >删除
          </el-button>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-controls">
    <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :total="totalRecords"
        :page-sizes="[1,2,4,8,10, 20, 30, 50]"
        layout="sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
    />
    </div>


    <div class="popup-container" :class="{ 'show-popup': showAddDialog }">
      <div class="popup-backdrop" @click="showAddDialog = false"></div>
      <div class="popup-dialog" :class="{ 'scale-in': showAddDialog }">
        <div class="popup-header">
          <div class="popup-title">
            <i class="fas fa-plus-circle header-icon"></i>
            <h3>新增过敏史</h3>
          </div>
          <button class="close-button" @click="showAddDialog = false">
            <i class="el-icon-close"></i>
          </button>
        </div>

        <el-form :model="initializeData" label-width="110px" class="popup-form">

          <el-form-item label="记录时间：" required>
            <el-date-picker
                v-model="initializeData.recordDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
                class="custom-date-picker"
                :popper-class="'custom-date-popper'"
            />
          </el-form-item>

          <el-form-item label="过敏原：" prop="medicationName" >
            <el-input
                v-model="initializeData.allergen"
                placeholder="请输入名称"
                class="custom-input"
                suffix-icon="el-icon-document"
            />
          </el-form-item>

          <el-form-item label="禁用药物：" prop="usageAndDosage" >
            <el-input
                v-model="initializeData.forbiddenDrugs"
                placeholder="例如：坤肉"
                class="custom-input"
                suffix-icon="el-icon-timer"
            />
          </el-form-item>

          <el-form-item label="治疗药物：" class="form-item-vertical">
            <el-input
                v-model="initializeData.treatmentDrugs"
                placeholder="请输入药物名称"
                type="textarea"
                :rows="3"
                class="custom-textarea"
            />
          </el-form-item>

          <el-form-item label="规避方法：" class="form-item-vertical">
            <el-input
                v-model="initializeData.avoidanceMethod"
                placeholder="请输入规避方法"
                type="textarea"
                :rows="3"
                class="custom-textarea"
            />
          </el-form-item>

          <el-form-item label="备注：" class="form-item-vertical">
            <el-input
                v-model="initializeData.remarks"
                placeholder="请输入备注"
                type="textarea"
                :rows="3"
                class="custom-textarea"
            />
          </el-form-item>
        </el-form>

        <div class="popup-footer">
          <el-button
              class="custom-cancel-btn"
              @click="showAddDialog = false"
          >取消
          </el-button>
          <el-button
              type="primary"
              class="custom-confirm-btn"
              @click="saveNewMedication"
          >保存记录
          </el-button>
        </div>
      </div>
    </div>
    <div class="total-records-notice">
      <el-icon>
        <info-filled/>
      </el-icon>
      您共有{{ totalRecords }}条用药记录
    </div>

  </div>
</template>

<script setup>
import {computed, nextTick, onMounted, onUnmounted, reactive, ref} from 'vue';
import {
  createHealthRecord,
  deleteHealthRecord,
  getAllergyHistory,
  getMedication,
  updateHealthRecord
} from "@/api/profile.js";
import { ElButton, ElForm, ElFormItem, ElInput, ElMessage, ElMessageBox, ElPagination } from 'element-plus';
import {InfoFilled} from "@element-plus/icons-vue";
import { postLog } from "@/api/log.js"

const editMode = ref(false);
const showAddDialog = ref(false);

const isSortedAscending = ref(true);
const sortButtonText = computed(() => isSortedAscending.value ? '按日期排序 ↑' : '按日期排序 ↓');

const medications = ref([]);
const originalMedications = ref([]);
const currentPage = ref(1);
const pageSize = ref(8);
const totalRecords = ref(0);
const isLoading = ref(false);
const isSampleData = ref(false);

// 数据初始化
const initializeData = reactive({
  recordId: null,
  recordDate: new Date().toISOString().split('T')[0],
  recordType: '过敏史',
  allergen: '',
  forbiddenDrugs: '',
  treatmentDrugs: '',
  avoidanceMethod: '',
  remarks: ''
});

// 用户状态监听
const userInfo = ref(null);
const handleUserLogout = () => {
  userInfo.value = null;
  medications.value = [];
};


// 生命周期钩子
onMounted(async () => {
  try {
    const storedUser = localStorage.getItem('currentUser');
    userInfo.value = storedUser ? JSON.parse(storedUser) : null;
    await loadMedications();
  } catch (error) {
    console.error('初始化失败:', error);
  }

  window.addEventListener('user-logout', handleUserLogout);
  window.addEventListener('storage', (e) => {
    if (e.key === 'currentUser' && !e.newValue) handleUserLogout();
  });
});

onUnmounted(() => {
  window.removeEventListener('user-logout', handleUserLogout);
});

// 保存逻辑
const saveChanges = async () => {

  try {
    const promises = medications.value.map(async (med) => {
      const submitData = {
        recordId: med.recordId,
        recordDate: med.recordDate,
        recordType: '过敏史',
        detail: `${med.allergen}|${med.forbiddenDrugs}|${med.treatmentDrugs}|${med.avoidanceMethod}|${med.remarks}`
      };
      return med.recordId
          ? await updateHealthRecord(submitData)
          : await createHealthRecord(userInfo.value?.id, submitData);
    });

    await Promise.all(promises);
    ElMessage.success('保存成功');
    editMode.value = false;
    await loadMedications();
    // 修改操作日志记录
    if (userInfo.value) {
      for (const med of medications.value) {
        await postLog({
          id: userInfo.value.id,
          role: userInfo.value.role,
          username: userInfo.value.username,
          ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
          loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
          recordType: '过敏史',
          action: '修改',
          recordId: med.recordId,
          logTime: new Date().toISOString() // 添加 logTime 属性
        });
      }
    }
  } catch (error) {
    ElMessage.error('保存失败：' + error.message);
  }
};

const addNewMedication = () => {
  console.log('新增按钮点击事件触发');
  Object.assign(initializeData, {
    recordId: null,
    recordDate: new Date().toISOString().split('T')[0],
    recordType: '过敏史',
    allergen: '',
    forbiddenDrugs: '',
    treatmentDrugs: '',
    avoidanceMethod: '',
    remarks: ''
  });

  // 触发对话框显示并添加动画类
  nextTick(() => {
    showAddDialog.value = true;
  });
};



const saveNewMedication = async () => {

  try {
    const submitData = {
      ...initializeData,
      detail: `${initializeData.allergen}|${initializeData.forbiddenDrugs}|${initializeData.treatmentDrugs}|${initializeData.avoidanceMethod}|${initializeData.remarks}`
    };
    const response = await createHealthRecord(userInfo.value?.id, submitData);
    ElMessage.success('新增成功');
    showAddDialog.value = false;
    await loadMedications();

    // 新增操作日志记录
    if (userInfo.value) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '过敏史',
        action: '新增',
        recordId: response.data?.data,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }
  } catch (error) {
    ElMessage.error('新增失败：' + error.message);
  }
};
const toggleSort = () => {
  loadMedications();
};
// 加载数据
const loadMedications = async () => {
  isLoading.value = true;
  try {
    const res = await getAllergyHistory(userInfo.value?.id, {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    });
    isSortedAscending.value = !isSortedAscending.value;
    res.data.data.sort((a, b) => {
      return isSortedAscending.value
          ? a.recordDate.localeCompare(b.recordDate)
          : b.recordDate.localeCompare(a.recordDate);
    });
    if (res.data?.data) {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;
      medications.value = res.data.data.slice(startIndex, endIndex);
      totalRecords.value = res.data.total || res.data.data.length;
      originalMedications.value = JSON.parse(JSON.stringify(res.data.data));
      isSampleData.value = false;
    }
  } catch (error) {
    isSampleData.value = true;
  } finally {
    isLoading.value = false;
  }
};

const cancelEdit = () => {
  editMode.value = false;
  medications.value = JSON.parse(JSON.stringify(originalMedications.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)));
};

const deleteHandler = async (index) => {
  try {
    await ElMessageBox.confirm('确定删除该过敏史记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const recordId = medications.value[index].recordId;
    if (recordId) {
      await deleteHealthRecord(recordId);
    }
    medications.value.splice(index, 1);
    ElMessage.success('删除成功');

    if (medications.value.length === 0 && currentPage.value > 1) {
      currentPage.value--;
      await loadMedications();
    }
    // 删除操作日志记录
    if (userInfo.value) {
      await postLog({
        id: userInfo.value.id,
        role: userInfo.value.role,
        username: userInfo.value.username,
        ip: userInfo.value.ip || '192.66.55.4', // 若 IP 不存在则设为空字符串
        loginTime: userInfo.value.loginTime || new Date().toISOString(), // 若 loginTime 不存在则设为当前时间
        recordType: '过敏史',
        action: '删除',
        recordId: recordId,
        logTime: new Date().toISOString() // 添加 logTime 属性
      });
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败：' + error.message);
  }
};
const handleSizeChange = (val) =>{
  pageSize.value = val;
  currentPage.value=1;
  loadMedications();
}
const handlePageChange = (page) => {
  currentPage.value = page;
  isSortedAscending.value = !isSortedAscending.value;

  loadMedications();

};
</script>

<style scoped>

@import "@/assets/css/new.css";

</style>